{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 计数排序( Counting sort )\n",
    "## 要求带排序的元素均为整数，介于 [0, k)  之间。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def Counting_sort(L,k):\n",
    "    '''\n",
    "    Input:\n",
    "    - L: the unordered list.\n",
    "    - k: the upper bound.\n",
    "    Output:\n",
    "    - List: the ordered list.\n",
    "    '''\n",
    "    B = [0 for i in range(k)]\n",
    "    for i in range(len(L)):\n",
    "        B[L[i]] += 1\n",
    "    for i in range(1,len(B)):\n",
    "        B[i] = B[i] + B[i-1]\n",
    "    List = [0 for i in range(len(L))]\n",
    "    for i in range(len(L)-1,-1,-1):\n",
    "        List[B[L[i]]-1] = L[i]\n",
    "        B[L[i]] -= 1\n",
    "    return List"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 1, 3, 3, 4, 4, 4, 6]\n"
     ]
    }
   ],
   "source": [
    "# running this to check counting sort\n",
    "L = [3,6,4,1,3,4,1,4]\n",
    "print(Counting_sort(L, 10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "torch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
